package com.dom.domweb.dao.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dom.common.constants.ConstantError;
import com.dom.common.enums.UserStatEnum;
import com.dom.common.exception.ServiceException;
import com.dom.common.model.vo.basic.*;
import com.dom.common.utils.BeanUtil;
import com.dom.domweb.dao.entity.TOrganInfo;
import com.dom.domweb.dao.entity.TRoleInfo;
import com.dom.domweb.dao.entity.TUserInfo;
import com.dom.domweb.dao.entity.TUserRoleRel;
import com.dom.domweb.dao.mapper.TUserInfoMapper;
import com.dom.domweb.dao.service.ITOrganInfoService;
import com.dom.domweb.dao.service.ITRoleInfoService;
import com.dom.domweb.dao.service.ITUserInfoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dom.domweb.dao.service.ITUserRoleRelService;
import com.dom.domweb.modular.shiro.model.ShiroUser;
import com.xiaoleilu.hutool.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * B_用户信息表 服务实现类
 * </p>
 *
 * @author xllei
 * @since 2018-11-17
 */
@Service
public class TUserInfoServiceImpl extends ServiceImpl<TUserInfoMapper, TUserInfo> implements ITUserInfoService {
    @Autowired
    private ITUserRoleRelService userRoleRelService;
    @Autowired
    private ITOrganInfoService organInfoService;
    @Autowired
    private ITRoleInfoService roleInfoService;

    @Override
    public TUserInfo getUserByUserName(String userName) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("user_name", userName);
        return selectOne(wrapper);
    }

    @Override
    public B079A findUserByPager(B079R request, ShiroUser user) {
        Wrapper<TUserInfo> wrapper = new EntityWrapper<>();
        if (ObjectUtil.isNull(user.getMemCode())) {
            throw new ServiceException(ConstantError.OPERATOR_USER_ILLEGAL);
        }
        wrapper.eq("mem_code", user.getMemCode());
        if(!ObjectUtils.isEmpty(request.getUserName())){
            wrapper.and().like("user_name", request.getUserName());
        }
        if (ObjectUtil.isNotNull(request.getOrganCode())) {
            wrapper.and().eq("organ_code", request.getOrganCode());
        }
        if (ObjectUtil.isNotNull(request.getStat())) {
            wrapper.and().eq("stat", request.getStat());
        }
        wrapper.orderBy("id", false);

        Page<TUserInfo> page = new Page<>();
        page.setCurrent(request.getPn());
        page.setSize(request.getPs());

        page = this.selectPage(page, wrapper);

        B079A response = new B079A();
        response.setTotalNum((int) page.getTotal());

        if (0 == page.getTotal()) {
            response.setUserInfoData(null);
            return response;
        }

        //获取机构信息
        List<TOrganInfo> organInfos = organInfoService.selectList(new EntityWrapper<TOrganInfo>().eq("mem_code", user.getMemCode()));
        Map<Integer, TOrganInfo> organMap = organInfos.stream().collect(Collectors.toMap(TOrganInfo::getId, entity -> entity));
        System.out.println(organInfos);

        System.out.println(organMap);
        //获取角色信息
        List<TRoleInfo> roleInfos = roleInfoService.findRoleList(user.getMemCode());
        Map<Integer, TRoleInfo> roleMap = roleInfos.stream().collect(Collectors.toMap(TRoleInfo::getId, entity -> entity));

        List<UserInfo> userInfos = new ArrayList<>();
        page.getRecords().forEach(userInfo -> {
            UserInfo newUser = new UserInfo();
            BeanUtil.copyPropertiesIgnoreNull(userInfo, newUser);
            newUser.setUserId(userInfo.getId());

            //map匹配机构、角色信息
            newUser.setRoleName((null != roleMap && 0 != roleMap.size() && null != roleMap.get(userInfo.getRoleCode())) ? roleMap.get(userInfo.getRoleCode()).getRoleName() : null);
            newUser.setOrganName((null != organMap && 0 != organMap.size() && null != organMap.get(userInfo.getOrganCode())) ? organMap.get(userInfo.getOrganCode()).getOrganName() : null);
            userInfos.add(newUser);
        });
        response.setUserInfoData(userInfos);
        return response;
    }

    @Override
    public B070A addUserInfo(B070R request, ShiroUser user) {
        if (ObjectUtil.isNull(user.getMemCode())) {
            throw new ServiceException(ConstantError.OPERATOR_USER_ILLEGAL);
        }

        TUserInfo userInfo = new TUserInfo();
        BeanUtil.copyPropertiesIgnoreNull(request, userInfo);
        userInfo.setMemCode(user.getMemCode());
        userInfo.setRoleCode(request.getRoleId());
        userInfo.setPasswd("12345");
        userInfo.setStat(0);

        this.baseMapper.insertReturnPrimary(userInfo);

        TUserRoleRel userRoleRel = new TUserRoleRel();
        userRoleRel.setUserId(userInfo.getId());
        userRoleRel.setMemCode(user.getMemCode());
        userRoleRel.setRoleId(userInfo.getRoleCode());
        userRoleRelService.insert(userRoleRel);

        B070A response = new B070A();
        response.setUserId(userInfo.getId());
        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public B072A editUserInfo(B072R request) {
        TUserInfo userInfo = new TUserInfo();
        BeanUtil.copyPropertiesIgnoreNull(request, userInfo);
        userInfo.setId(request.getUserId());
        userInfo.setMtime(new Date());

        //修改用户信息
        boolean result = this.updateById(userInfo);

        //修改用户角色信息
        Wrapper<TUserRoleRel> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userInfo.getId())
                .last("limit 1");
        TUserRoleRel userRoleRel = userRoleRelService.selectOne(wrapper);
        if (ObjectUtil.isNull(userInfo)) {
            throw new ServiceException(ConstantError.NO_ROLE_ERROR);
        }
        userRoleRel.setRoleId(request.getRoleCode());
        boolean roleResult = userRoleRelService.updateById(userRoleRel);

        B072A response = new B072A();
        response.setUserId(userInfo.getId());
        return response;
    }

    @Override
    public B071A delUserInfo(B071R request) {
        TUserInfo userInfo = this.selectById(request.getUserId());
        if (ObjectUtil.isNull(userInfo)) {
            throw new ServiceException(ConstantError.NO_USER_ERROR);
        }
        userInfo.setStat(UserStatEnum.USER_STAT_STOP.getCode());
        userInfo.setMtime(new Date());

        boolean result = this.updateById(userInfo);
        B071A response = new B071A();
        response.setUserId(userInfo.getId());
        return response;
    }
}
